<template>
  <div
    id="statisticsChart"
    ref="chart"
    style="width: 100%; height: 240px; margin-top: 10px; user-select: none"
  ></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "StatisticsChart",
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      let nameList = ["新维煤矿"];
      let dataList = [10];

      const options = {
        color: ["#7F8AF2"],
        grid: {
          left: "0%",   // 增加左侧空间放置名称
          right: "15%",  // 增加右侧空间放置次数
          top: "0%",
          bottom: "0%",
          containLabel: true,
        },
        xAxis: {
          show: false,
          type: "value",
        },
        yAxis: [
          {
            show: true,
            type: "category",
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            inverse: true,  // 排序
            axisLabel: {
              show: true,
              color: "#fff",
              fontSize: 14,
              align: "center",
              padding: [0, 0, 0, -20],  // 调整标签位置
              verticalAlign: "middle",
              formatter: function(value) {
                // 名称左对齐
                return `{name|${value}}`;
              },
              rich: {
                name: {
                  width: 60,
                  align: 'left'
                }
              }
            },
            data: nameList,
          }
        ],
        series: [
          {
            type: "bar",
            data: dataList,
            showBackground: true,
            backgroundStyle: {
              borderRadius: 40,
            },
            barWidth: 15,
            itemStyle: {
              borderRadius: 10,
            },
            label: {
              show: true,
              position: 'right',  // 次数显示在柱形图右侧
              formatter: '{c}次',
              color: '#fff',
              fontSize: 14,
              offset: [0, 0]  // 调整标签位置
            },
            yAxisIndex: 0  // 使用第一个y轴
          }
        ]
      };

      this.chart.setOption(options);
      window.addEventListener("resize", this.handleResize);
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
  }
};
</script>
